package org.lee.mq.util;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * @author jackielee
 * @version 1.0
 * @description StringUtil
 * @date 2021/6/3
 **/
public class StringUtil {
    private static String FORMATTER_SYMBOL = "{}";
    private static char FORMATTER_SYMBOL_LEFT = '{';
    private static char FORMATTER_SYMBOL_RIGHT = '}';

    public static List<String> split(String source, String delimiter) {
        if (source == null || source.isEmpty()) {
            return new ArrayList<>();
        }
        return Arrays.asList(source.split(delimiter));
    }

    public static boolean isEmpty(String str) {
        return str == null || str.trim().isEmpty();
    }

    public static boolean isNotEmpty(String str) {
        return !isEmpty(str);
    }

    public static String trim(String str) {
        if (isEmpty(str)) {
            return "";
        }
        return str.trim();
    }

    public static String Uuid() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    public static String getExt(String fileName) {
        int index;
        if (isEmpty(fileName) || (index = fileName.indexOf('.')) == -1) {
            return "";
        }
        return fileName.substring(index);
    }

    public static String checkObsFileKey(String fileKey) {
        if (isEmpty(fileKey)) {
            return fileKey;
        }
        fileKey = trim(fileKey);
        int sep = fileKey.indexOf('/');
        if (sep == 0) {
            return fileKey.substring(sep + 1);
        }
        return fileKey;
    }

    /**
     * 格式化{}内容字符串
     *
     * @param format 含 {} 字符串格式
     * @param args   参数
     * @return String
     */
    public static String format(String format, Object... args) {
        if (isEmpty(format) || format.indexOf(FORMATTER_SYMBOL) == -1 || args.length == 0) {
            return format;
        }
        StringBuilder sb = new StringBuilder(format.length() + args.length * 5);
        int len = format.length();
        int argIndex = 0;
        List<Object> argList = Arrays.asList(args);
        for (int i = 0; i < len; ++i) {
            char c = format.charAt(i);
            if (c == FORMATTER_SYMBOL_LEFT && i < len - 1) {
                char c2 = format.charAt(i + 1);
                if (c2 == FORMATTER_SYMBOL_RIGHT && argIndex < argList.size()) {
                    sb.append(argList.get(argIndex++));
                    i++;
                    continue;
                }
            }
            sb.append(c);
        }
        return sb.toString();
    }
}
